package com.redxun.filter;

import com.redxun.core.auth.properties.SecurityProperties;
import com.redxun.core.boot.util.TokenUtil;
import com.redxun.core.common.constant.SecurityConstants;
import com.redxun.core.common.model.DefaultUser;
import com.redxun.core.common.utils.SpringUtil;
import com.redxun.core.share.util.CookieUtil;
import com.redxun.core.tool.BeanUtil;
import com.redxun.core.tool.StringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @author: szw
 * @Description: 自定义忽略url但必须带上token网关全局过滤器
 * @Date: Created in 2020/10/13.
 */
@Slf4j
public class HttpTokenRequestFilter implements Filter {
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        SecurityProperties securityProperties = SpringUtil.getBean(SecurityProperties.class);
        HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
        
        log.debug("----自定义忽略url但必须带上token网关全局过滤器生效----");
        String reqUrl = httpRequest.getRequestURL().toString();
        //reqUrl是否是httpTokenUrls校验url带token
        boolean isConTianUrl = securityProperties.getIgnore().obtainsHttpTokenUrl(reqUrl);
        if (isConTianUrl) {
            String accessToken = CookieUtil.getValue(httpRequest, SecurityConstants.AUTHORIZATION_TOKEN);
            if (StringUtils.isNotEmpty(accessToken)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
            Map<String, String[]> queryParams = httpRequest.getParameterMap();
            if (BeanUtil.isEmpty(queryParams)) {
                log.error("---HttpTokenRequestFilter.filter is error : accessToken is null");
                throw new IllegalStateException("Invalid URI query: accessToken is null");
            }
            accessToken = httpRequest.getParameter("accessToken");
            if (StringUtils.isEmpty(accessToken)) {
                log.error("---HttpTokenRequestFilter.filter is error : accessToken is null");
                throw new IllegalStateException("Invalid URI query: accessToken is null");
            }
            DefaultUser loginUser = TokenUtil.getLoginUser(accessToken);
            if (BeanUtil.isEmpty(loginUser)) {
                log.error("---HttpTokenRequestFilter.filter is error : accessToken is invalid !");
                throw new IllegalStateException("Invalid URI query: accessToken is invalid !");
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
